/*!
 * App Object.
 */
var $_app = $();

$_app.params = [];

$_app.getParametersFromURL = function(url){
	if (url.match(/https?[^?]+\?([^#]*)/)) {
		var q = RegExp.$1;
		var a = q.split('&')
		for (var n in a) {
			if (a[n].match(/^([^=]+)=(.*)$/)) {
				$_app.params[RegExp.$1] = decodeURIComponent(RegExp.$2);
			}
		}
	}
	return $_app.params;
}

$_app.statusMessage = function(xhr){
	$_app.$status.text('');

	var d = new Date();
	$_app.$status.append(d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());

	var url = location.protocol + '//' + location.host + $_app.uri;
	$_app.$status.append($('<strong/>').append(' ' + $_app.method + ' ' + url));

	var s = $('<span/>').append(' status:' + xhr.status);
	(xhr.status!=200)? $_app.$status.attr('class','err'):$_app.$status.attr('class','');
	$_app.$status.append(s);
}

$_app.help = function(){
	//TODO
	$('body').append('TODO:セットアップ手順を書く');
}

$_app.initialize = function(){
	//check
	$_app.getParametersFromURL(location.href);
	if(!$_app.params['docType']) return $_app.help();

	//title
	$('title').append('jsonengine data viewer');

	//style
	var _css = $('<style type="text/css"/>')
		.append('#filter{width:100%;}')
		.append('#data input{width:100%;cursor:pointer;}')
		.append('#_CLEAR{margin-left:1em;}')
		.append('.err strong{color:red;}')
		;
	$('head').append(_css);

//後でソースを丸ごと追加する/////////////////////////////////////////////////////////////
	//script
	var _js = $('<script type="text/javascript" src="uneval.js"/>');
	$('head').append(_js);

	//init body
	var b = $('body');
	b.append($('<h1/>').text($_app.params['docType']));
	b.append($('<textarea id="filter"></textarea>'));
	b.append($('<button id="_GET">GET</button>'));
	b.append($('<button id="_GET_ALL">GET_ALL</button>'));
	b.append($('<button id="_CLEAR">CLEAR</button>'));
	b.append($('<br/>'));
	b.append($('<br/>'));
	b.append($('<button id="_POST">POST</button>'));
	b.append($('<button id="_PUT">PUT</button>'));
	b.append($('<button id="_DELETE">DELETE</button>'));
	b.append($('<p id="status"/>'));
	b.append($('<p id="data"/>'));

	//bind object
	$_app.$filter = $('#filter');
	$_app.$get    = $('#_GET');
	$_app.$get_all= $('#_GET_ALL');
	$_app.$clear  = $('#_CLEAR');
	$_app.$post   = $('#_POST');
	$_app.$put    = $('#_PUT');
	$_app.$delete = $('#_DELETE');
	$_app.$status = $('#status');
	$_app.$data   = $('#data');

	return 1;
}

$_app.createForm = function(o) {
	var form = $('<p/>');
	
	for (var k in o) 
		if(k!='_docId' && k!='_updatedAt' && k!='_createdAt')
			form.append($('<p/>').append($('<p/>').append(k + ':' + o[k])));
	return form;
}

$_app.checkBeforeGET = function(){
	var f = $_app.$filter.val().trim();
	(f.substr(0,1)=='/')? $_app.isQuery='':$_app.isQuery='?';
	return 1;
}

$_app.checkBeforeGET_ALL = function(){
	return 1;
};

$_app.checkBeforePOST = function(){
	if($_app.$filter.val().trim()=='')
		return confirm('パラメータは空です。空のデータを作成しますか？')? 1:0;
	return 1;
}

$_app.checkBeforePUT = function(){
	if($_app.$filter.val().trim()=='')
		return alert('パラメータは空です。');
	return 1;
}

$_app.checkBeforeDELETE = function(){
	if($_app.$filter.val().trim()=='')
		return confirm('パラメータは空です。全権削除しますか？')? 1:0;
	return 1;
}

$_app.createList = function(json, status, xhr){
	$_app.statusMessage(xhr);
	$_app.$data.empty();
	if(Object.prototype.toString.call(json)=='[object Array]'){
		$.each(json, function(){
			var o = this;
			var i = $('<input class="expand"/>').click(function(){
				if(i.attr('class')){
					i.attr('class', null);
					i.after($_app.createForm(o));
				}else{
					i.attr('class', 'expand');
					$(this.parentNode.childNodes[1]).remove();
				}
			});
			var d = $('<div/>').append(i.val(uneval(this).slice(1, -1) || ''));
			$('#data').append(d);
		});
	}
	else if(Object.prototype.toString.call(json)=='[object Object]'){
		var i = $('<input class="expand"/>').click(function(){
			if(i.attr('class')){
				i.attr('class', null);
				i.after($_app.createForm(json));
			}else{
				i.attr('class', 'expand');
				$(this.parentNode.childNodes[1]).remove();
			}
		});
		var d = $('<div/>').append(i.val(uneval(json).slice(1, -1) || ''));
		$('#data').append(d);
	}
}

$_app.errorMessage = function(xhr, status){
	$_app.statusMessage(xhr);
	$_app.$data.empty();
}

//jQueryオブジェクトの拡張
var $je = $();
$je.extend({
	hello: function(){
		console.log('Hello world.');
	}
});
$je.hello();

/*!
 * app main
 */
$(document).ready(function(){

	if(!$_app.initialize())return;

	$_app.$clear.click(function(){
		$_app.$filter.val('');
	});

	$_app.$get.click(function(){
		if(!$_app.checkBeforeGET())return;
		$_app.uri = '/_je/' + $_app.params['docType'] + $_app.isQuery + $_app.$filter.val();
		$_app.method = 'GET';
		$.ajax({
			url: $_app.uri,
			type: $_app.method,
			success: $_app.createList,
			error: $_app.errorMessage
		});
	});

	$_app.$get_all.click(function(){
		if(!$_app.checkBeforeGET_ALL())return;
		$_app.uri = '/_je/' + $_app.params['docType'];
		$_app.method = 'GET';
		$.ajax({
			url: $_app.uri,
			type: $_app.method,
			success: $_app.createList,
			error: $_app.errorMessage
		});
	});

	$_app.$post.click(function(){
		if(!$_app.checkBeforePOST())return;
		$_app.uri = '/_je/' + $_app.params['docType'] + '?' + $_app.$filter.val();
		$_app.method = 'POST';
		$.ajax({
			url: $_app.uri,
			type: $_app.method,
			success: $_app.createList,
			error: $_app.errorMessage
		});
	});

	$_app.$put.click(function(){
		if(!$_app.checkBeforePUT())return;
		$_app.uri = '/_je/' + $_app.params['docType'] + '?' + $_app.$filter.val();
		$_app.method = 'PUT';
		$.ajax({
			url: $_app.uri,
			type: $_app.method,
			success: $_app.createList,
			error: $_app.errorMessage
		});
	});

	$_app.$delete.click(function(){
		if(!$_app.checkBeforeDELETE())return;
		$_app.uri = '/_je/' + $_app.params['docType'] + '/' + $_app.$filter.val();
		$_app.method = 'DELETE';
		$.ajax({
			url: $_app.uri,
			type: $_app.method,
			success: $_app.createList,
			error: $_app.errorMessage
		});
	});

});

